﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CE.Database;
using System.Data;
using CE.Global;
using System.Collections;

public partial class carinsurance_CheckAgentCallStatus : System.Web.UI.Page
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
        {
            Response.Redirect("~/carinsurance/PendingApplication.aspx");
        }

        if (!Page.IsPostBack)
        {
            ddlOrderBy.SelectedIndex = 0;
            LoadAgentList();
            ddlAgentList.Text = Session[General.UserId].ToString();
            LoadCallStatus();
            //ddlCallStatus.Text = "1";
            RefreshGridView();

            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() != "100"
                || Session[CE.Global.General.UserId].ToString() == "1499") //Broker 2 is Supervisor        
            {
                ddlCallStatus.Items.Clear();
                ddlCallStatus.Items.Add(new ListItem(Resources.General.NewLead, "1"));
                ddlCallStatus.Items.Add(new ListItem(Resources.General.Pending, "4")); ;
                ddlCallStatus.Items.Add(new ListItem(Resources.General.Callback, "2"));
                
            }
            else
            {
                btnConfirmAssignToOtherAgent.Visible = false;
            }
        }

        if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "100"
            && Session[CE.Global.General.UserId].ToString() != "1499") //Broker 2 is Supervisor
        {
            ddlAgentList.Enabled = false;
        }

    }

    private void LoadAgentList()
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            DataTable _dt = new DataTable("tblList");
            string _spName = "sprocCXCRMGetAgentList";

            SortedList paraList = new SortedList();
            paraList.Add("@AgentID", Session[General.UserId].ToString());
            _dt = _db.GetDataTableBySP(_spName, paraList);

            ddlAgentList.Items.Clear();
           
            if (_dt != null && _dt.Rows.Count > 0)
            {
                
                for (int i = 0; i < _dt.Rows.Count; i++)
                {
                    ddlAgentList.Items.Add(new ListItem(_dt.Rows[i]["FULLNAME"].ToString(), _dt.Rows[i]["CEID"].ToString()));
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
            throw;
        }
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        RefreshGridView();

        if (ddlCallStatus.Text == "4" || ddlCallStatus.Text == "2")
        {
            btnConfirmAssignToOtherAgent.Enabled = true;
        }
        else
        {
            btnConfirmAssignToOtherAgent.Enabled = false;
        }
    }

    protected void btnConfirmAssignToOtherAgent_Click(object sender, EventArgs e)
    {
        MyDatabase _db = new MyDatabase();
        string _strUpdate = string.Empty;
        foreach (GridViewRow r in GridView1.Rows)
        {
            DropDownList ddlAssignToOtherAgent = (DropDownList)r.FindControl("ddlAssignToOtherAgent");

            if (ddlAssignToOtherAgent.Text != "-1")
            {
                Label lblAgentLeadID = (Label)r.FindControl("lblAgentLeadID");
                Label lblCustomerID = (Label)r.FindControl("lblCustomerID");
                Label lblCarID = (Label)r.FindControl("lblCarID");
                Label lblCallTypeID = (Label)r.FindControl("lblCallTypeID");


                _strUpdate = "Update tblCXCRMCallStatus "
                                + " SET CallBackAgentID = " + ddlAssignToOtherAgent.Text
                                + " , Remark = Remark + " + "'\n\r[" + Session[General.UserName].ToString() + " reassigned at  " + dateTimeNow.ToString("dd-MMM-yyyy hh:mm tt") + "]'" 
                                + " WHERE AgentLeadID = " + lblAgentLeadID.Text
                                + " AND CustomerID = " + lblCustomerID.Text
                                + " AND CarID = " + lblCarID.Text
                                + " AND CallTypeID = " + lblCallTypeID.Text;
                

                _db.ExecuteNonSqlStatement(_strUpdate);
            }
        }

        RefreshGridView();
    }

    protected void chkAssignToOtherAgent_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chk = (CheckBox)sender;
        GridViewRow gr = (GridViewRow)chk.Parent.Parent.Parent.Parent;
        
        DropDownList ddlAssignToOtherAgent = (DropDownList)gr.FindControl("ddlAssignToOtherAgent");
        ddlAssignToOtherAgent.Enabled = chk.Checked;

        if (ddlAssignToOtherAgent.Enabled)
        {
            foreach (ListItem l in ddlAgentList.Items)
            {
                if (l.Text.ToLower().Contains("broker") && !l.Selected)
                {
                    ddlAssignToOtherAgent.Items.Add(l);
                }
            }
        }
        else
        {
            ddlAssignToOtherAgent.Items.Add(new ListItem("No change", "-1"));
        }

        
    }

    private void RefreshGridView()
    {
        //<asp:SqlDataSource ID="sqlDSCallStatusDetail" runat="server" ConnectionString="<%$ ConnectionStrings:CX_CRMDBConnectionString %>"
        //    SelectCommand="sprocCXCRMAgentCallScheduleStatusDetails" SelectCommandType="StoredProcedure">
        //    <SelectParameters>
        //        <asp:ControlParameter ControlID="ddlAgentList" Name="AgentID" PropertyName="SelectedValue"
        //            Type="Int64" />
        //        <asp:ControlParameter ControlID="ddlCallType" Name="CallType" PropertyName="SelectedValue"
        //            Type="Int64" />
        //        <asp:ControlParameter ControlID="ddlCallStatus" Name="CallStatus" PropertyName="SelectedValue"
        //            Type="Int16" />
        //        <asp:ControlParameter ControlID="lblLangOption" Name="LangOption" PropertyName="text"
        //            Type="Int16" />
        //        <asp:ControlParameter ControlID="ddlOrderBy" Name="OrderBy" PropertyName="text" Type="Int16" />
        //    </SelectParameters>
        //</asp:SqlDataSource>

        DataTable _dtSummary = new DataTable();
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        string _spName = "[sprocCXCRMAgentCallScheduleStatusDetails]";
        SortedList _sPara = new SortedList();

        _sPara.Add("@AgentID", ddlAgentList.SelectedValue);
        _sPara.Add("@CallType", ddlCallType.SelectedValue);
        _sPara.Add("@CallStatus", ddlCallStatus.SelectedValue);
        _sPara.Add("@LangOption", 1);
        _sPara.Add("@OrderBy", ddlOrderBy.SelectedValue);

        _dtSummary = _db.GetDataTableBySP(_spName, _sPara);

        GridView1.DataSource = _dtSummary;
        GridView1.DataBind();
        if (GridView1.Rows.Count > 0)
        {
            btnPrint.Visible = true;
            lblRecordCount.Text = "(" + GridView1.Rows.Count.ToString() + ") record(s). " + Resources.General.DateTime + ": " + dateTimeNow.ToString("dd-MMM-yyyy hh:mm tt") + "&nbsp;&nbsp;"; //DateTime.Now.ToString("dd-MMM-yyyy hh:mm tt")
        }
        else
        {
            btnPrint.Visible = false;
            lblRecordCount.Text = "(" + GridView1.Rows.Count.ToString() + ") record(s). " + Resources.General.DateTime + ": " + dateTimeNow.ToString("dd-MMM-yyyy hh:mm tt") + "&nbsp;&nbsp;"; //DateTime.Now.ToString("dd-MMM-yyyy hh:mm tt")
        }
    }

    protected void ddlOrderBy_SelectedIndexChanged(object sender, EventArgs e)
    {
        btnRefresh_Click(null, null);
    }

    private Int32 GetOverDueCount()
    {
        Int32 _result = 0;
        MyDatabase _myDb = new MyDatabase();
        DataTable _dtOverDue = new DataTable("tblOverDue");
        _dtOverDue = _myDb.GetDataTable(@"SELECT COUNT(*) RecordCount FROM tblCXCRMCallStatus WHERE ((CONVERT(VARCHAR(8), ModifiedDate+1, 112) >= '20120801' AND ModifiedDate+1 <= dbo.fn_getUTCDateTime() AND CallFinishType = 3 AND AgentId = " + ddlAgentList.Text + ") OR (CONVERT(VARCHAR(8), CallBackDateTime, 112) >= '20120801' AND CallBackDateTime <= dbo.fn_getUTCDateTime() AND CallFinishType = 2 AND CallBackAgentId = " + ddlAgentList.Text + "))");

        if (_dtOverDue != null && _dtOverDue.Rows.Count > 0)
        {
            _result = Convert.ToInt32(_dtOverDue.Rows[0]["RecordCount"].ToString());
        }
        return _result;
    }

    private void LoadCallStatus()
    {
        Int32 OverDue = GetOverDueCount();
        
        if (OverDue <= 40)
        {
            ddlCallStatus.Items.Clear();
            ddlCallStatus.Items.Add(new ListItem(Resources.General.NewLead, "1"));
            ddlCallStatus.Items.Add(new ListItem(Resources.General.Pending, "4")); ;
            ddlCallStatus.Items.Add(new ListItem(Resources.General.Callback, "2"));
            ddlCallStatus.Items.Add(new ListItem("ยังไม่หมดประกัน > 60วัน", "10"));
        }
        else
        {
            ddlCallStatus.Items.Clear();
            ddlCallStatus.Items.Add(new ListItem(Resources.General.Pending, "4"));
            ddlCallStatus.Items.Add(new ListItem(Resources.General.Callback, "2"));
            ddlCallStatus.Items.Add(new ListItem("ยังไม่หมดประกัน > 60วัน", "10"));
        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink hplCallNow = (HyperLink)e.Row.FindControl("hplCallNow");

            Label lblAgentLeadID = (Label)e.Row.FindControl("lblAgentLeadID");
            Label lblCustomerID = (Label)e.Row.FindControl("lblCustomerID");
            Label lblCarID = (Label)e.Row.FindControl("lblCarID");
            Label lblCallTypeID = (Label)e.Row.FindControl("lblCallTypeID");

            
            DropDownList ddlAssignToOtherAgent = (DropDownList)e.Row.FindControl("ddlAssignToOtherAgent");
            Literal litAssignToOtherAgent = (Literal)e.Row.FindControl("litAssignToOtherAgent");
            if (ddlCallStatus.Text == "4" || ddlCallStatus.Text == "2")
            {
                if (Session[General.UserRole] != null && Session[General.UserRole].ToString() != "100"
                    || Session[CE.Global.General.UserId].ToString() == "1499") //Broker 2 is Supervisor        
                {
                    foreach (ListItem l in ddlAgentList.Items)
                    {
                        if (l.Text.ToLower().Contains("broker") && !l.Selected)
                        {
                            ddlAssignToOtherAgent.Items.Add(l);
                        }
                    }
                }
                else
                {
                    ddlAssignToOtherAgent.Visible = false;
                    litAssignToOtherAgent.Visible = false;
                }
            }
            else
            {
                ddlAssignToOtherAgent.Visible = false;
                litAssignToOtherAgent.Visible = false;
            }

            Literal lblCallTypeDesc = (Literal)e.Row.FindControl("lblCallTypeDesc");
            Literal lblCallStatusDesc = (Literal)e.Row.FindControl("lblCallStatusDesc");
            string leadID = DataBinder.Eval(e.Row.DataItem, "AgentLeadID").ToString();
            lblAgentLeadID.Text = leadID.ToString();
            string callType = DataBinder.Eval(e.Row.DataItem, "CallType").ToString();
            lblCallTypeID.Text = callType;
            string carID = DataBinder.Eval(e.Row.DataItem, "CarID").ToString();
            lblCarID.Text = carID;
            string customerID = DataBinder.Eval(e.Row.DataItem, "CustomerID").ToString();
            lblCustomerID.Text = customerID;
            string callStatus = DataBinder.Eval(e.Row.DataItem, "Status").ToString();
            hplCallNow.NavigateUrl = "offline/ViewCINoMatchFound.aspx?leadid=" + leadID + "&calltype=" + callType + "&carid=" + carID + "&custid=" + customerID;

            switch (callType)
            {
                case "100":
                    lblCallTypeDesc.Text = "<span style='color:black;'>" + Resources.General.FirstFollowUpCall + "</span>";
                    break;
                case "101":
                    lblCallTypeDesc.Text = "<span style='color:black;'>" + Resources.General.CallMeRequest + "</span>";
                    break;
                case "102":
                    lblCallTypeDesc.Text = "<span style='color:black;'>" + Resources.General.CallMeBack + "</span>";
                    break;
                case "103":
                    lblCallTypeDesc.Text = "<span style='color:black;'>" + Resources.General.CallDirect + "</span>";
                    break;
                default: lblCallTypeDesc.Text = "N/A"; break;
            }

            switch (callStatus)
            {
                case "1":
                    lblCallStatusDesc.Text = "<span style='color:red;'>" + Resources.General.Pending + "</span>";
                    break;
                case "2":
                    if (DataBinder.Eval(e.Row.DataItem, "countback").ToString() == "")
                    {
                        lblCallStatusDesc.Text = Resources.General.Callback + " <span style='color:red;'>[" + Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "CallBackDateTime").ToString()).ToString("dd/MMM/yyyy hh:mm tt") + "]</span>";
                    }
                    else
                    {
                        int countBack = Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "countback"));
                        if (countBack <= 0)
                        {
                            countBack = Math.Abs(countBack);
                        }
                        else
                        {
                            countBack = -(countBack);
                        }
                        lblCallStatusDesc.Text = Resources.General.Callback + " <span style='color:red;'>[" + Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "CallBackDateTime").ToString()).ToString("dd/MMM/yyyy hh:mm tt") + "] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; เหลืออีก " + countBack.ToString() + " วัน</span>";
                    }
                    break;
                case "3":
                    lblCallStatusDesc.Text = "<span style='color:green;'>" + Resources.General.FollowUp + "</span>";
                    break;
                default:
                    lblCallStatusDesc.Text = "N/A";
                    break;
            }

        }
    }
}
